package com.chain.BrotherExchange.ui.fragment;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.CoinOrderList;
import com.chain.BrotherExchange.data.model.EntrustQueue;
import com.chain.BrotherExchange.data.model.Quotation;
import com.chain.BrotherExchange.event.LoginEvent;
import com.chain.BrotherExchange.event.LogoutEvent;
import com.chain.BrotherExchange.event.UserAssetsChangeEvent;
import com.chain.BrotherExchange.event.VisualQuotationEvent;
import com.chain.BrotherExchange.ui.activity.LoginActivity;
import com.chain.BrotherExchange.ui.activity.MyOrderActivity;
import com.chain.BrotherExchange.ui.activity.VisualQuotationActivity;
import com.chain.BrotherExchange.ui.adapter.CoinTransactionAdapter;
import com.chain.BrotherExchange.ui.adapter.CoinOrderListAdapter;
import com.chain.BrotherExchange.ui.adapter.TextWatcherAdapter;
import com.chain.BrotherExchange.ui.core.BaseFragment;
import com.chain.BrotherExchange.ui.window.QuotationPopupWindow;
import com.chain.BrotherExchange.ui.listener.LoginInterceptListener;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.CoinViewModel;
import com.chain.BrotherExchange.viewmodel.OrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.chain.BrotherExchange.widget.QuantityView;
import com.example.common.widget.state.NetworkStateLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;

/**
 * 币币交易
 */
public class CoinFragment extends BaseFragment implements OnLoadmoreListener {

    @Bind(R.id.increase_view) View mIncreaseView;
    @Bind(R.id.minus_view) View mMinusView;

    @Bind(R.id.buy_sell_number_edit) EditText mBuySellNumberEditText;
    @Bind(R.id.purchasable_text_view) TextView mPurchasableTextView;
    @Bind(R.id.buy_unit_text) TextView mBuyUnitTextView;
    @Bind(R.id.minimum_purchase_layout) View mMinimumPurchaseLayout;
    @Bind(R.id.raise_price_layout) View mRaisePriceLayout;
    @Bind(R.id.buy_or_sale_text_view) TextView mBuyOrSaleTextView;
    @Bind(R.id.price_select_view) View mPriceSelectView;
    @Bind(R.id.look_all_delegates_view) View mLookAllDelegatesView;
    @Bind(R.id.buy_sell_cny_price_text) TextView mBuySellCnyPriceText;
    @Bind(R.id.buy_sell_price_edit_text) EditText mBuySellPriceEditView;
    @Bind(R.id.balance_text_view) TextView mBalanceTextView;
    @Bind(R.id.price_text) TextView mPriceTextView;
    @Bind(R.id.balance_percent_group) RadioGroup mBalancePercentGroup;
    @Bind(R.id.buy_sale_group) RadioGroup mBuySaleGroup;
    @Bind(R.id.buy_or_sale_view) TextView mBuyOrSaleView;
    @Bind(R.id.cny_price_text) TextView mCnyPriceTextView;
    @Bind(R.id.coin_type_text) TextView mCoinTypeTextView;
    @Bind(R.id.volatility_text) TextView mVolatilityTextView;
    @Bind(R.id.order_record_list) RecyclerView mOrderRecordList;
    @Bind(R.id.show_quotation_layout) ViewGroup mShowQuestionLayout;
    @Bind(R.id.coin_delegation_list) RecyclerView mCoinDelegationList;
    @Bind(R.id.question_info_item_layout) View mQuestionInfoItemLayout;
    @Bind(R.id.smart_refresh_layout) SmartRefreshLayout mSmartRefreshLayout;
    @Bind(R.id.network_state_layout) NetworkStateLayout mNetworkStateLayout;
    @Bind(R.id.volatility_layout) View mVolatilityLayout;
    @Bind(R.id.entrust_queue_state_layout) NetworkStateLayout mEntrustQueueStateLayout;

    private CoinViewModel mCoinViewModel;
    private OrderViewModel mOrderViewModel;
    private ListPopupWindow mListPopupWindow;
    private int mDefaultSelectTransactionType;
    private CoinOrderListAdapter mOrderListAdapter;
    private QuotationPopupWindow mQuotationPopupWindow;
    private CoinTransactionAdapter mEntrustQueueAdapter;

    @Override
    protected void onVisible() {
        ActivityBarHelper.setTransparentDarkColorStatus(getActivity());
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_coin;
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void initActions() {
        mOrderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
        mCoinViewModel = ViewModelProviders.of(this).get(CoinViewModel.class);

        // 上拉加载
        mSmartRefreshLayout.setEnableRefresh(false);
        mSmartRefreshLayout.setOnLoadmoreListener(this);

        // 初始化未完成委托订单列表
        initUnfinishedEntrustView();

        // 交易行情窗口
        initQuestionWindowView();

        // 初始化选择价格类型方式视图：市价或限价
        initSelectEntrustTypeView();

        // 初始化交易方式视图：买入或卖出
        initSelectTransactionTypeView();

        // 初始委托记录视图
        initEntrustListView();

        // 委托订单
        mBuyOrSaleView.setOnClickListener(new LoginInterceptListener(v -> entrustOrders()));

        // 改变折合数量
        QuantityView.modify(mIncreaseView, mMinusView, mBuySellPriceEditView);

        // 加载折合数量
        mCoinViewModel.equivalentNumber().observe(this, equivalentNumber ->
                mBuySellPriceEditView.setText(equivalentNumber)
        );

        // 加载折合价格
        mCoinViewModel.equivalentPrice().observe(this, price ->
                mBuySellCnyPriceText.setText("≈" + price + "CNY"));

        // 加载可买或可卖数量
        mCoinViewModel.purchasableNumber().observe(this, number ->
                mPurchasableTextView.setText(number));

        // 加载可用余额
        mCoinViewModel.availableBalance().observe(this, balance ->
                mBalanceTextView.setText(balance));

        // 加载实际购买数量
        mCoinViewModel.actualPurchasableNumber().observe(this, number ->
                mBuySellNumberEditText.setText(number));

        // 购买或卖出货币符号
        mCoinViewModel.getNumberTokenSymbol().observe(this, symbol ->
                mBuyUnitTextView.setText(symbol));

        // 改变折合数量
        mBuySellPriceEditView.addTextChangedListener(new TextWatcherAdapter(text ->
                mCoinViewModel.setEquivalentNumber(text.toString())));

        // 清除百分比
        mBuySellNumberEditText.addTextChangedListener(new TextWatcherAdapter(text -> {
            //mBalancePercentGroup.clearCheck();
            //mCoinViewModel.purchasableNumberPercent(0);
        }));

        // 选择实际购买数量百分比
        mBalancePercentGroup.setOnCheckedChangeListener((group, checkedId) -> {
                    if (checkedId != -1) {
                        mCoinViewModel.purchasableNumberPercent(Double.parseDouble((String)
                                group.findViewById(checkedId).getTag()));
                    }
                }
        );
    }

    private void initUnfinishedEntrustView() {
        mOrderListAdapter = new CoinOrderListAdapter();
        mCoinDelegationList.setAdapter(mOrderListAdapter);
        mCoinDelegationList.setItemAnimator(new DefaultItemAnimator());

        // 取消未完成订单
        initCancelUnfinishedCoinOrder();

        // 查看所有委托
        mLookAllDelegatesView.setOnClickListener(new LoginInterceptListener(
                v -> MyOrderActivity.launch(getContext())));

        // 获取未完成订单列表
        newUnfinishedCoinOrder();
        mNetworkStateLayout.setOnAnewRequestNetworkListener(this::newUnfinishedCoinOrder);
    }

    private void initSelectEntrustTypeView() {
//        mPriceSelectView.setOnClickListener(v -> mListPopupWindow.show());
//        mListPopupWindow = new ListPopupWindow(getContext());
//        mListPopupWindow.setAnchorView(mPriceSelectView);
//        mListPopupWindow.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,
//                android.R.id.text1, new String[]{"市价交易", getString(R.string.limit_prices)}));
//
//        mListPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
//            mListPopupWindow.dismiss();
//            mBuyOrSaleTextView.setText(((TextView) view).getText().toString());
//
//            if (position == 0) {
//                mCoinViewModel.toggleEntrustType(C.API_MARKET_PRICE);
//                mMinimumPurchaseLayout.setVisibility(View.VISIBLE);
//                mRaisePriceLayout.setVisibility(View.GONE);
//            } else {
                mCoinViewModel.toggleEntrustType(C.API_LIMITED_PRICE);
                mMinimumPurchaseLayout.setVisibility(View.GONE);
                mRaisePriceLayout.setVisibility(View.VISIBLE);
//            }
//        });
    }

    private void initSelectTransactionTypeView() {
        mBuySaleGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.buy_type_button:
                    mCoinViewModel.toggleTransactionType(C.API_ENTRUST_BUY);
                    mBuyOrSaleView.setText(R.string.buying);
                    mBuyOrSaleView.setBackgroundResource(R.drawable.shape_rect_drop);
                    break;
                case R.id.sale_type_button:
                    mCoinViewModel.toggleTransactionType(C.API_ENTRUST_SELL);
                    mBuyOrSaleView.setText(R.string.sale);
                    mBuyOrSaleView.setBackgroundResource(R.drawable.shape_rect_warning);
                    break;
            }
        });

        initDefaultSelectTransactionType(mDefaultSelectTransactionType);
    }

    private void initDefaultSelectTransactionType(int type) {
        if (type == C.API_ENTRUST_SELL) {
            mBuySaleGroup.check(R.id.sale_type_button);
        } else {
            mBuySaleGroup.check(R.id.buy_type_button);
        }
    }

    /**
     * 初始化行情视图
     */
    private void initQuestionWindowView() {
        if (mQuotationPopupWindow == null) {
            mQuotationPopupWindow = new QuotationPopupWindow(this);
            mQuotationPopupWindow.setOnItemClickListener(this::loadQuestion);
            mShowQuestionLayout.setOnClickListener(v -> mQuotationPopupWindow.show(
                    mQuestionInfoItemLayout)
            );
        }
    }

    private void loadQuestion(Quotation.DataBean.ListBean list) {
        // 当前行情信息
        mCoinTypeTextView.setText(list.getSymbol());
        mPriceTextView.setText(list.getPrice());
        mCnyPriceTextView.setText(list.getCny_price());
        mVolatilityTextView.setText(list.getScope());
        mVolatilityLayout.setBackgroundResource(list.getScopeBackground());
        mPriceTextView.setTextColor(Color.parseColor(list.getScopeColor()));

        // 获取买卖盘记录
        mCoinViewModel.requestEntrustedRecordList(list.getSymbol(), list.getToken_id(),
                list.getToken_trade_id());

        // 跳转K线
        mVolatilityLayout.setOnClickListener(v -> VisualQuotationActivity.launch(
                v.getContext(), list.getSymbol()));
    }

    // 初始化委托列表视图
    public void initEntrustListView() {
        mEntrustQueueAdapter = new CoinTransactionAdapter();
        mOrderRecordList.setAdapter(mEntrustQueueAdapter);

        // 委托记录列表
        initEntrustQueueList();
        mEntrustQueueStateLayout.setOnAnewRequestNetworkListener(this::initEntrustQueueList);

        // 选择价格
        mEntrustQueueAdapter.setOnItemClickListener((parent, view, position, id) ->
                new LoginInterceptListener(v -> {
                    EntrustQueue.DataBean.Bean item = mEntrustQueueAdapter.getItem(position);
                    mCoinViewModel.selectBuySellData(item);
                }).onClick(view)
        );
    }

    private void initEntrustQueueList() {
        // 委托记录列表
        mCoinViewModel.entrustQueue().observe(this, resource ->
                Resource.load(getContext(), resource, mEntrustQueueStateLayout, result ->
                        mEntrustQueueAdapter.setCoinTransactionList(result.getBuy(), result.getSell())
                )
        );
    }

    // 委托订单
    private void entrustOrders() {
        String price = mBuySellPriceEditView.getText().toString();
        String number = mBuySellNumberEditText.getText().toString();
        mCoinViewModel.entrustOrders(price, number)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(getContext(), R.string.message_submitting_request);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            // 重新加载
                            mQuotationPopupWindow.performClick();

                            // 重新加载未完成订单
                            newUnfinishedCoinOrder();

                            // 刷新用户资产
                            EventBus.getDefault().post(new UserAssetsChangeEvent());

                            // 关闭键盘
                            Androids.hiddenSoftInputFromWindow(getContext(), mBuySellNumberEditText);
                            mBuySellNumberEditText.setFocusable(true);
                            mBuySellNumberEditText.setFocusableInTouchMode(true);
                        }
                    }
                });
    }

    // 取消订单
    private void initCancelUnfinishedCoinOrder() {
        mOrderListAdapter.setCancelClickListener((parent, view, position, id) -> {
            CoinOrderList.DataBean.ListBean bean = mOrderListAdapter.getItem(position);
            mOrderViewModel.cancelCoinOrder(bean.getEntrust_id()).observe(this, resource -> {
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    bean.setStates(C.API_ENTRUST_ORDER_CANCEL_STATE);
                    mOrderListAdapter.notifyItemChanged(position);
                }
            });
        });
    }

    // 未完成订单列表
    private void newUnfinishedCoinOrder() {
        mOrderViewModel.newUnfinishedCoinOrder().observe(this, resource ->
                Resource.load(getContext(), resource, mNetworkStateLayout, result ->
                        mOrderListAdapter.setOrder(result)
                )
        );
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mOrderViewModel.moreUnfinishedCoinOrder().observe(this, resource -> {
            switch (resource.state) {
                case EMPTY:
                    Androids.makeText(R.string.no_more);
                    break;
                case NOT_NETWORK:
                    Androids.makeText(R.string.network_error);
                    break;
                case ERROR:
                    Androids.makeText(resource.message);
                    break;
                case SUCCESS:
                    mOrderListAdapter.addOrder(resource.source);
                    break;
                case TOKEN_ERROR:
                    EventBus.getDefault().post(new LogoutEvent());
                    LoginActivity.launch(getContext());
                    break;
            }

            mSmartRefreshLayout.finishLoadmore(0);
        });
    }

    @Subscribe
    public void loginEvent(LoginEvent event) {
        newUnfinishedCoinOrder();

        String symbol = mCoinTypeTextView.getText().toString();
        if (!TextUtils.isEmpty(symbol)){
            mQuotationPopupWindow.setDefaultQuotation(symbol);
            mQuotationPopupWindow.resetViews();
        }
    }

    @Subscribe
    public void logoutEvent(LogoutEvent event) {
        mNetworkStateLayout.setVisibility(View.GONE);
    }

    @Subscribe(sticky = true)
    public void visualQuotationEvent(VisualQuotationEvent event) {
        mDefaultSelectTransactionType = event.type;

        if (mQuotationPopupWindow != null) {
            mQuotationPopupWindow.setDefaultQuotation(event.market.getSymbol());
            mQuotationPopupWindow.resetViews();
        } else {
            initQuestionWindowView();
            mQuotationPopupWindow.setDefaultQuotation(event.market.getSymbol());
        }

        if (mCoinViewModel != null) {
            initDefaultSelectTransactionType(mDefaultSelectTransactionType);
        }
    }

    public static Fragment newInstance() {
        return new CoinFragment();
    }
}
